package com.prototype.deepclone;

import java.io.*;

/**
 * @author zhupanlin
 * @version 1.0
 * @description: TODO
 * @date 2024/4/13 15:05
 */
public class DeepProtoType implements Serializable, Cloneable {
    
    public String name; // String
    public DeepCloneableTarget deepCloneableTarget; // 引用

    public DeepProtoType() {
    }
    
    // 深拷贝 - 方式1 使用clone 方法

    @Override
    protected Object clone() throws CloneNotSupportedException {
        Object deep = null;
        // 先完成对基本数据类型(属性)的克隆
        deep = super.clone();
        
        // 对引用类型的属性，进行单独处理
        DeepProtoType deepProtoType = (DeepProtoType) deep;
        deepProtoType.deepCloneableTarget = (DeepCloneableTarget) deepProtoType.deepCloneableTarget.clone();
        
        return deepProtoType;
    }
    
    // 深拷贝 - 方式2 通过对象的序列化实现(推荐)
    
    public Object deepClone() {
        // 创建流对象
        ByteArrayOutputStream bos = null;
        ObjectOutputStream oos = null;
        ByteArrayInputStream bis = null;
        ObjectInputStream ois = null;
        DeepProtoType copyobj = null;
        
        try {
            
            // 序列化
            bos = new ByteArrayOutputStream();
            oos = new ObjectOutputStream(bos);
            // 当前这个对象以对象流的方式输出
            oos.writeObject(this);
            
            // 反序列化
            bis = new ByteArrayInputStream(bos.toByteArray());
            ois = new ObjectInputStream(bis);
            copyobj = (DeepProtoType) ois.readObject();
            return copyobj;
        }catch (Exception e){
            e.printStackTrace();
            return null;
        } finally {
            // 关闭流
            try {
                if (bos != null){
                    bos.close();
                }
                oos.close();
                bis.close();
                ois.close();
            } catch (Exception e){
                e.printStackTrace();
            }
        }
    }
}
